package com.rjhch.tonglink.server.jms.http;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

public class QueueSenderTest {
    public static final String tcf = "tongtech.jms.jndi.JmsContextFactory";/* initial context factory*/
    public static final String remoteURL = "http://127.0.0.1:10026";
    public static final String remoteFactory = "HttpConnectionFactory";

	public static void main(String[] args) {
		ConnectionFactory testConnFactory = null;
		Connection myConn = null;
		Session mySession = null;
		Queue testQueue = null;
		MessageProducer testProducer = null;
		MessageConsumer testConsumer = null;
		TextMessage testMessage = null;

		try {

			Properties pro = new Properties();

			pro.setProperty("java.naming.factory.initial", tcf);
			pro.setProperty("java.naming.provider.url", remoteURL);
			
			javax.naming.Context ctx = new javax.naming.InitialContext(pro);

			testConnFactory = (ConnectionFactory) ctx.lookup(remoteFactory);
			testQueue = (Queue) ctx.lookup("lq1");
			
			myConn = testConnFactory.createConnection();
			mySession = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			testProducer = mySession.createProducer(testQueue);
			testConsumer = mySession.createConsumer(testQueue);
			testMessage = mySession.createTextMessage("QueueSender Message");
			myConn.start();
//			testMessage.setBooleanProperty("JMS_TONG_Encrypted", true);//需要加密时使用, 仅LOCAL支持
//			testMessage.setBooleanProperty("JMS_TONG_Compressed", true);//需要压缩时使用, 仅LOCAL支持

			System.out.println("发送消息...");
			testProducer.send(testMessage);
			System.out.println("发送完成...");
			System.out.println("SUCCESS.");
			TextMessage msg = (TextMessage)testConsumer.receive(2000);
			System.out.println(msg.getText());
		} catch (Exception jmse) {
			System.out.println("Exception oxxurred :" + jmse.toString());
			jmse.printStackTrace();
		} finally {
			try {
				if (mySession != null) {
					mySession.close();
				}
				if (myConn != null) {
					myConn.close();
				}
			} catch (Exception e) {
				System.out.println("退出时发生错误。");
				e.printStackTrace();
			}
		}

	}

	public static void usage(String error) {
		
		if (error != null) {
			System.out.println(error);
		}
		System.out.println("Usage: QueueSender -protocol <local|remote>");
		System.out.println("\tprotocol: protocol type, local or remote");
	}
}
